package es.decoroso.communicationAgent.behaviours;

import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jade.proto.states.MsgReceiver;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import es.decoroso.communicationAgent.CommunicationAgent;
import es.decoroso.communicationAgent.bean.Message;

public class ProcessMessage extends MsgReceiver {

	static private MessageTemplate template = MessageTemplate
			.MatchPerformative(ACLMessage.INFORM);
	private CommunicationAgent agent;

	public ProcessMessage(CommunicationAgent agent) {
		super(agent, template, MsgReceiver.INFINITE, null, null);
		this.agent = agent;
		System.out.println("Starting process message behaviour");
	}

	@Override
	protected void handleMessage(ACLMessage message) {
		if (message == null) {
			reset(template, MsgReceiver.INFINITE, null, null);
			return;
		}
		
		JSONObject js = null;
		try {
			js = (JSONObject) new JSONTokener(message.getContent().toString()).nextValue();
		} catch (JSONException e) {
			System.out.println("Can not cast JSONObject");
			e.printStackTrace();
			reset(template, MsgReceiver.INFINITE, null, null);
		}

		Message ms = new Message(js);
		
		agent.treatMessage(ms);
		reset(template, MsgReceiver.INFINITE, null, null);
	}
}
